<template>
  <div class="echarts-box">
    <div id="myEcharts" :style="{ width: '420px', height: '360px' }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted, watchEffect } from 'vue'
import { FunnelChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
import { getFunnelData } from '@/api/dashboard'

echarts.use([FunnelChart, CanvasRenderer])

//   new Date()获取当前时间转成yyyy-mm-dd格式
const currentDate = new Date()
const year = currentDate.getFullYear()
const month = ('0' + (currentDate.getMonth() + 1)).slice(-2)
const day = ('0' + currentDate.getDate()).slice(-2)
const formattedDate = year + '-' + month + '-' + day
// console.log(formattedDate)
//    定义获取基础数据、今日简报、待办事项数据的参数
const params = {
  beginCreateTime: '2023-05-17',
  endCreateTime: formattedDate
}

//   echarts漏斗图数据接收
const funnelData = ref('')

//    echarts漏斗图数据获取
const getFunnelDatas = async () => {
  const res = await getFunnelData(params)
  funnelData.value = res.data
  // console.log(funnelData)
}
export default {
  name: 'App',
  setup() {
    let myEcharts = echarts
    onMounted(() => {
      initChart()
      getFunnelDatas()
    })
    onUnmounted(() => {
      myEcharts.dispose
    })
    function initChart() {
      const chart = myEcharts.init(document.getElementById('myEcharts'), 'purple-passion')

      watchEffect(() => {
        // 计算漏斗图数据数组
        const data = [
          { value: 60, name: `客户数 ${funnelData.value?.clientNumber}` },
          { value: 40, name: `商机数 ${funnelData.value?.businessNumber}` },
          { value: 80, name: `有效线索数 ${funnelData.value?.clueNumberEffective}` },
          { value: 100, name: `线索总数 ${funnelData.value?.clueNumber}` }
        ]

        chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: (params) => `${params.name} 个`
          },
          series: [
            {
              type: 'funnel',
              left: '10%',
              width: '65%',
              min: 40,
              max: 100,
              minSize: '40%',
              maxSize: '100%',
              data: data
            }
          ]
        })
      })
      window.onresize = function () {
        chart.resize()
      }
    }
    return {
      initChart
    }
  }
}
</script>
